package tmotan

import (
	"encoding/json"
	"github.com/weibocom/motan-go"
	"github.com/weibocom/motan-go/core"
	"strconv"
)

type Client struct {
	Ctx *motan.MCContext
}

var (
	GClient    *Client
	GMCContext *motan.MCContext
)

func NewClient(conf string) (client *Client) {

	client = &Client{}
	ctx := motan.GetClientContext(conf)
	ctx.Start(nil)
	client.Ctx = ctx
	GMCContext = ctx
	GClient = client
	return

}

//调用常规或带有token的方法
func (Cli *Client) Call(path, method string, args interface{}, token ...map[string]string) (ret string, err error) {
	client := Cli.Ctx.GetClient(path)
	var replay []byte
	req := client.BuildRequest(method, []interface{}{args})
	if len(token) > 0 {
		tk := token[0]
		for k, v := range tk {
			req.SetAttachment(k, v)

		}
	}
	err = client.BaseCall(req, &replay)
	return string(replay), err
}

//调用id creator
func (Cli *Client) CallIdCreator() (ret string, err error) {
	client := Cli.Ctx.GetClient("call_proxy")
	var replay []byte
	req := client.BuildRequest("/v1/IdCreator", []interface{}{})
	req.SetAttachment("T_Method", "POST")
	err = client.BaseCall(req, &replay)
	return string(replay), err
}

func setHeaders(req core.Request, headers ...map[string]string) {
	if len(headers) > 0 {
		for k, v := range headers[0] {
			req.SetAttachment(k, v)
		}
		traceId, _ := headers[0]["traceId"]
		if base, ok := req.(*core.MotanRequest); ok {
			uuid, _ := strconv.ParseUint(traceId, 10, 63)
			base.RequestID = uuid
			base.MethodDesc = traceId

		}

	}
}

//这个方法是给client使用的
// local agent <- CallOpenApi <- gin.RpcProxy <- motan_server<-CallRpcProxy
//call_proxy 这一组配置中包含了整个com.xxx,yyy.service.IdCreatorService下的所有服务
func (Cli *Client) CallRpcProxy(uri string, params map[string]string, headers ...map[string]string) (ret string, err error) {
	client := Cli.Ctx.GetClient("call_proxy")

	var replay []byte
	strParams, err := json.Marshal(params)
	if err != nil {
		return
	}
	req := client.BuildRequest("/v1/RpcAgentProxy", []interface{}{strParams})
	req.SetAttachment("T_Method", "POST")
	req.SetAttachment("T_Uri", uri)
	setHeaders(req, headers...)
	//log.Printf("%+v",req)

	err = client.BaseCall(req, &replay)
	return string(replay), err
}
